<template>
  <div
    style="
      padding: 10px 0px;
      background-color: rgb(239, 238, 238);
      height: 100%;
      overflow-y: auto;
    "
  >
    <div style="min-height: 50px; background-color: #fff; border-radius: 5px">
      <!-- <div style="background-color: aliceblue;height: 35px;line-height: 35px;padding-left:20px;font-size: 18px;">单检材分析</div> -->
      <el-row style="padding: 10px 20px">
        <el-col :span="12"
          ><div class="grid-content bg-purple">
            <!-- <span style="font-size:15px;">选择检材：</span>
                <el-select :popper-append-to-body="false" @change="selectFunction()"  v-model="value1" placeholder="请选择活动区域">
                    <el-option :label="item" :value="item" v-for="(item,index) in proofList" :key="index"></el-option>
                </el-select> -->
            <!-- <span style="font-size:15px;">时间区间：</span> -->
            <el-date-picker
              v-model="value2"
              type="daterange"
              :append-to-body="false"
              style="margin-left: 20px"
              align="right"
              unlink-panels
              value-format="timestamp"
              range-separator="-"
            :start-placeholder="$t('analyze.startTime')"
            :end-placeholder="$t('analyze.endTime')"
              :picker-options="pickerOptions"
            >
            </el-date-picker></div
        ></el-col>
        <el-col :span="12"
          ><div
            style="display: flex; align-items: center"
            class="grid-content bg-purple-light"
          >
            <!-- <el-button @click="setKeyWord">设置关键字</el-button> -->
            <el-select
              :popper-append-to-body="false"
              style="width: 450px"
              v-model="selectedItems"
              multiple
              :collapse-tags="true"
            >
              <el-option-group
                v-for="group in options"
                :label="group.trigger_class"
                :key="group.trigger_class"
              >
                <el-option
                  v-for="item in group.children"
                  :label="item.trigger_value"
                  :value="item.trigger_value"
                  :key="item.trigger_value"
                >
                </el-option>
              </el-option-group>
            </el-select>
            <el-button
              style="margin-left: 20px"
              type="primary"
              @click="searchFunction"
              >{{$t('analyze.search')}}</el-button
            >
          </div></el-col
        >
      </el-row>
    </div>
    <div
      class=""
      style="
        min-height: 420px;
        margin-top: 10px;
        background-color: #fff;
        padding-top: 15px;
        display: flex;
        border-radius: 5px;
      "
    >
      <div
        style="
          width: 30%;
          border-right: 1px solid rgb(191, 191, 191);
          height: 400px;
          padding: 0 10px 10px 30px;
          display: flex;
        "
      >
        <!-- <div style="width: 50%">
          <miqie
            v-if="pirData"
            :pirData="pirData"
            :value1="value1"
            :value2="value2"
            :selectedItems="selectedItems"
          />
        </div> -->
        <div style="width: 100%">
          <pieBox
            ref="pieBox"
            v-if="pirData"
            :pirData="pirData"
            :value1="value1"
            :value2="value2"
            :selectedItems="selectedItems"
          />
        </div>
        <!-- <pieBox  /> -->
      </div>
      <div style="width: 70%">
        <div
          style="
            min-height: 50px;
            display: flex;
            align-items: center;
            padding: 0 20px;
          "
        >
          <el-button @click="chooseClass('全部')" size="small">{{$t('analyze.all')}}</el-button>
          <el-button
            @click="chooseClass(item)"
            size="small"
            v-for="(item, index) in options"
            :key="index"
            >{{ item.trigger_class }}</el-button
          >
        </div>
        <caregory
          ref="caregory"
          v-if="keyList"
          :keyList="keyList"
          :value1="value1"
          :value2="value2"
          :selectedItems="selectedItems"
        />
      </div>
    </div>

    <div
      v-if="show"
      style="
        width: 100%;
        min-height: 410px;
        background-color: #fff;
        margin-top: 10px;
        padding: 15px;
        border-radius: 5px;
      "
    >
      <el-tabs v-model="activeName">
        <el-tab-pane :label="$t('analyze.miqielianxiren')" name="first">
          <div style="font-size: 18px; font-weight: bold; margin-bottom: 10px">
            {{$t('analyze.miqielianxiren')}}：
          </div>
          <el-table
            :data="smsList"
            border
            stripe
            height="700"
            style="width: 100%"
          >
            <el-table-column :label="$t('analyze.appname')" prop="app_name" width="180">
              <template slot-scope="scope">
                <div v-if="scope.row.model == 'wechat'">{{$t('analyze.wechat')}}</div>
                <div v-else-if="scope.row.model == 'sms'">{{$t('analyze.sms')}}</div>
                <div v-else-if="scope.row.model == 'CallRecords'">{{$t('analyze.tonghuajilu')}}</div>
                <div v-else-if="scope.row.model == 'qq'">{{$t('analyze.QQ')}}</div>
                <div v-else>{{$t('wechat.mailList')}}</div>
              </template>
            </el-table-column>
            <el-table-column :label="$t('analyze.liaotianObjict')" prop="app_name">
              <template slot-scope="scope">
                <div v-if="scope.row.nick">{{$t('analyze.mingheng')}}：{{ scope.row.nick }}</div>
                <div v-if="scope.row.CONTACTNAME">
                  {{$t('analyze.account')}}：{{ scope.row.CONTACTNAME }}
                </div>
                <div v-if="scope.row.model == 'CallRecords'">
                  {{$t('analyze.phone')}}：{{ scope.row.phone }}
                </div>
              </template>
            </el-table-column>
            <el-table-column :label="$t('analyze.msgNumber')" prop="cnt" width="180">
            </el-table-column>
            <el-table-column :label="$t('analyze.endchatTime')" prop="address" width="180">
              <template slot-scope="scope">
                <div slot="reference" class="name-wrapper">
                  <el-tag size="mini">{{
                    formateDate(scope.row.infoTime)
                  }}</el-tag>
                  <div style="margin-top: 10px"></div>
                </div>
              </template>
            </el-table-column>
            <!-- <el-table-column label="最后一条消息" prop="content"> </el-table-column> -->
            <el-table-column label="操作" width="100">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  @click="handleEdit(scope.$index, scope.row)"
                  >{{$t('analyze.positionTem')}}</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane :label="$t('analyze.keyword')" name="second">
          <el-table
            :data="tableData"
            ref="keyGj"
            height="600"
            :empty-text="$t('analyze.keywordTip')"
            border
            style="width: 100%"
          >
            <el-table-column
              prop="app_name"
              :label="$t('analyze.leibie')" 
              width="120"
              align="center"
            >
              <template slot-scope="scope">
                <div v-if="scope.row.model == 'wechat'">{{$t('analyze.wechat')}}</div>
                <div v-else-if="scope.row.model == 'sms'">{{$t('analyze.sms')}}</div>
                <div v-else-if="scope.row.model == 'qq'">{{$t('analyze.QQ')}}</div>
                <div v-else>{{$t('wechat.mailList')}}</div>
              </template>
            </el-table-column>
            <el-table-column prop="" :label="$t('analyze.chufa')" width="200">
              <template slot-scope="scope">
                <div>{{$t('analyze.guanjiancileibie')}}：{{ scope.row.trigger_class }}</div>
                <div>{{$t('analyze.guanjianci')}}：{{ scope.row.trigger_value }}</div>
                <div>{{$t('analyze.chufaduixiang')}}：{{ scope.row.nick }}</div>
                <div>
                  {{$t('analyze.isQunChat')}}：{{ scope.row.isChatRoom == 0 ? "否" : "是" }}
                </div>
                <div>
                  {{$t('analyze.chufaTime')}}：{{
                    scope.row.infoTime == 0
                      ? formateDate(scope.row.infoTime)
                      : "暂无时间"
                  }}
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="content" :label="$t('analyze.lastMsg')">
            </el-table-column>
            <el-table-column fixed="right" label="操作" width="100">
              <template slot-scope="scope">
                <el-button
                  @click="jumpContent(scope.row)"
                  type="text"
                  size="small"
                  >{{$t('analyze.positionTem')}}</el-button
                >
              </template>
            </el-table-column>
          </el-table>

          <div class="block" style="margin-top: 10px">
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="offset"
              :page-sizes="[20, 50, 100, 150]"
              :page-size="limit"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
            >
            </el-pagination>
          </div>
        </el-tab-pane>
        <el-tab-pane :label="$t('analyze.appmingzhong')" name="three">
          <el-table
            :data="tableList"
            ref="AppPie"
            height="600"
            border
            :empty-text="$t('analyze.dianjiApp')"
            style="width: 100%"
          >
            <el-table-column
              prop="app_name"
              :label="$t('analyze.chufa')"
              width="120"
              align="center"
            >
            </el-table-column>
            <el-table-column prop="" :label="$t('analyze.leibie')" width="200">
              <template slot-scope="scope">
                <div>{{$t('analyze.guanjiancileibie')}}：{{ scope.row.trigger_class }}</div>
                <div>{{$t('analyze.guanjianci')}}：{{ scope.row.trigger_value }}</div>
                <div>{{$t('analyze.chufaduixiang')}}：{{ scope.row.nick }}</div>
                <div>
                  {{$t('analyze.isQunChat')}}：{{ scope.row.isChatRoom == 0 ? "否" : "是" }}
                </div>
                <div>
                 {{$t('analyze.chufaTime')}}：{{
                    scope.row.infoTime !== 0
                      ? formateDate(scope.row.infoTime)
                      : "暂无时间"
                  }}
                </div>
                <div v-if="scope.row.otherPhone">
                  {{$t('analyze.chufaObjectPhone')}}：{{ scope.row.otherPhone }}
                </div>
                <!-- <div>触发时间：{{scope.row.infoTime!==0?formateDate(scope.row.infoTime):'暂无时间'}}</div> -->
                <!-- <div>分析：{{scope.row.type==1?'人脉圈子':'联系人或者通话记录'}}</div> -->
              </template>
            </el-table-column>
            <el-table-column prop="content" :label="$t('analyze.lastMsg')">
            </el-table-column>
          </el-table>

          <div class="block" style="margin-top: 10px">
            <el-pagination
              @size-change="handleSizeChangeApp"
              @current-change="handleCurrentChangeApp"
              :current-page="appOffset"
              :page-sizes="[20, 50, 100, 150]"
              :page-size="appLimit"
              layout="total, sizes, prev, pager, next, jumper"
              :total="totalApp"
            >
            </el-pagination>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script>
import moment from "moment";
import tagBox from "./tagBox.vue";
import caregory from "./category.vue";
import pieBox from "./pieBox.vue";
import miqie from "./miqie.vue";
import {
  getEchartsData,
  getSelectKeyList,
  getProofListApi,
  getKeyList,
  smsAppListApi,
} from "@/api/proofOnly/index";
import { parseTime } from "@/utils/index";

export default {
  name: "proof",
  components: {
    tagBox,
    caregory,
    pieBox,
    miqie,
  },
  data() {
    return {
      tableList: [],
      activeName: "first",
      show: true,
      smsList: [],
      proofList: [],
      selectedItems: [],
      options: [
        {
          label: "Group 1",
          items: [
            { label: "Item 1-1", value: "item1-1" },
            { label: "Item 1-2", value: "item1-2" },
          ],
        },
        {
          label: "Group 2",
          items: [
            { label: "Item 2-1", value: "item2-1" },
            { label: "Item 2-2", value: "item2-2" },
          ],
        },
        // Add more groups as needed
      ],
      tableData: [],
      tabPosition: "top",
      activeKey: "1",
      visible: false,
      moment,
      value1: "",
      value3: "",
      pickerOptions: {
        shortcuts: [
          {
            text: this.$t('analyze.yizhou'),
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: this.$t('analyze.yizhou'),
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: this.$t('analyze.zuijinsangeyue'),
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      value1: "",
      value2: "",
      pirData: "",
      keyList: "",
      offset: 1,
      limit: 20,
      total: 0,
      appOffset: 1,
      appLimit: 20,
      totalApp: 0,
      trigger_class: "",
    };
  },
  created() {
    this.getProofList();
  },
  methods: {
    chooseClass(item) {
      if (item == "全部") {
        this.trigger_class = "";
        this.ininselectData();
      } else {
        this.trigger_class = item.trigger_class;
        this.ininselectData();
      }
    },
    handleSizeChangeApp(val) {
      this.appLimit = val;
      this.$refs.pieBox.initOffsetApp(this.appOffset, this.appLimit);
    },
    handleCurrentChangeApp(val) {
      this.appOffset = val;
      this.$refs.pieBox.initOffsetApp(this.appOffset, this.appLimit);
      this.$nextTick(() => {
        this.$refs.AppPie.bodyWrapper.scrollTop = 0;
      });
    },
    initPieDataList(list, total) {
      this.tableList = list;
      this.totalApp = total;
      this.activeName = "three";
    },
    jumpContent(row) {
      const proof_num = row.proofNum;
      // const phoneNumber = Number(row.otherPhone);
      let dd = row;
      switch (dd.model) {
        case "contact":
          dd.list_offset = 1;
          dd.list_limit = 20;
          dd.msg_offset = 1;
          dd.app_name = dd.phone ? dd.phone : dd.otherPhone;
          dd.proof_num = proof_num;
          break;
        case "sms":
          dd.list_offset = 1;
          dd.list_limit = 20;
          dd.msg_offset = 1;
          dd.app_name = dd.phone ? dd.phone : dd.otherPhone;
          dd.proof_num = proof_num;
          dd.searchKey = dd.trigger_value;
          break;
        case "wechat":
          dd.list_offset = 1;
          dd.list_limit = 20;
          dd.msg_offset = 1;
          dd.app_name = dd.isChatRoom == 0 ? "好友" : "群组";
          dd.proof_num = proof_num;
          dd.account_id = dd.ACCOUNT_ID;
          dd.username = dd.username;
          dd.contact_username = dd.CONTACTNAME;
          dd.msgtime = dd.infoTime;
          dd.id = dd.tid;
          break;
        case "qq":
          dd.list_offset = 1;
          dd.list_limit = 20;
          dd.msg_offset = 1;
          dd.app_name = dd.isChatRoom == 0 ? "好友" : "群组";
          dd.proof_num = proof_num;
          dd.account_id = dd.ACCOUNT_ID;
          dd.username = dd.username;
          dd.label = dd.username;
          dd.contact_username = dd.SENDERNICK;
          dd.msgtime = dd.infoTime;
          dd.id = dd.tid;
          break;
        case "chattantan":
          dd.list_offset = 1;
          dd.list_limit = 20;
          dd.msg_offset = 1;
          dd.app_name = dd.nick;
          dd.proof_num = proof_num;
          dd.account_id = dd.ACCOUNT_ID;
          dd.username = dd.nick;
          dd.label = dd.username;
          dd.model = 'other_app';
          dd.class = '探探';
          dd.contact_username = dd.CONTACTNAME;
          dd.msgtime = dd.infoTime;
          dd.id = dd.tid;
          break;
        default:
          break;
      }
      // 储存类型
      sessionStorage.setItem("model", dd.model);
      // 储存节点数据
      sessionStorage.setItem("sumData", JSON.stringify(dd));
      // 激活跳转组件
      this.$store.commit("SET_ORDERDATA", Date.parse(new Date()));
      sessionStorage.setItem("only", true);
      this.visible = false;
      // this.$router.push({ name: "Dashboard"});
      // this.$parent.changeContent();
      this.$emit('change-content');
    },
    handleSizeChange(val) {
      this.limit = val;
      this.$refs.caregory.initOffsetLimit(this.offset, this.limit);
      // this.$nextTick(() => {
      //     this.$refs.keyGj.bodyWrapper.scrollTop = 0;
      //   })
    },
    handleCurrentChange(val) {
      this.offset = val;
      this.$refs.caregory.initOffsetLimit(this.offset, this.limit);
      this.$nextTick(() => {
        this.$refs.keyGj.bodyWrapper.scrollTop = 0;
      });
    },
    childrenFunction(list, total) {
      this.tableData = list;
      this.total = total;
      this.activeName = "second";
    },
    childrenFunction1(list, total) {
      this.offset = 1;
      this.tableData = list;
      this.total = total;
      this.activeName = "second";
    },
    selectFunction() {
      // this.getProofList()
      this.initKeyListFn();
    },
    formateDate(date) {
      return parseTime(date);
    },
    smsListDataApi() {
      let data = {
        proof_num: this.value1,
      };
      smsAppListApi(data)
        .then((res) => {
          this.smsList = res.data;
        })
        .catch((err) => {});
    },
    initKeyListFn() {
      let data = {
        proof_num: this.value1,
        // starttime:this.value2[0]?this.value2[0]:0,
        // endtime:this.value2[1]?this.value2[1]:2000000000,
      };
      this.options = [];
      this.selectedItems = [];
      getKeyList(data)
        .then((res) => {
          res.data.forEach((group) => {
            for (const key in group) {
              if (group.hasOwnProperty(key)) {
                const children = group[key].map((item) => {
                  return { trigger_value: item };
                });

                this.options.push({ trigger_class: key, children });
                this.selectedItems.push(...group[key]);
              }
            }
            this.initEchartData();
            this.ininselectData();
            this.smsListDataApi();
          });
        })
        .catch((err) => {});
    },
    getProofList() {
      this.value1 = sessionStorage.getItem("analyzeProof");
      this.initKeyListFn();
      // getProofListApi({}).then(res=>{
      //   if(res.data.length>0){
      //     this.proofList = res.data;
      //     this.value1 = res.data[0]
      //     this.initKeyListFn();

      //   }
      // }).catch(res=>{

      // })
    },
    searchFunction() {
      this.initEchartData();
      this.ininselectData();
      // this.smsListDataApi();
    },
    ininselectData() {
      let data = {};
      try {
        data = {
          proof_num: this.value1,
          starttime: this.value2[0] ? this.value2[0] / 1000 : 0,
          endtime: this.value2[1] ? this.value2[1] / 1000 : 2000000000,
          trigger_value: this.selectedItems.join(","),
          trigger_class: this.trigger_class,
        };
      } catch (error) {
        data = {
          proof_num: this.value1,
          starttime: 0,
          endtime: 2000000000,
          trigger_value: this.selectedItems.join(","),
          trigger_class: this.trigger_class,
        };
      }

      let arr = [];
      getSelectKeyList(data)
        .then((res) => {
          // for (let index = 0; index < res.data.length; index++) {
          //   const element = res.data[index];
          //     arr.push(element.trigger_value)
          // }
          // this.selectedItems = arr;
          // return
          this.keyList = res.data;
          return;
          // this.options = formatData(res.data);
          function formatData(originalData) {
            // 使用 reduce 函数进行数组转换
            const formattedData = originalData.reduce((result, item) => {
              // 查找是否已存在该 trigger_class 的项
              const existingItem = result.find(
                (formattedItem) =>
                  formattedItem.trigger_class === item.trigger_class
              );

              // 如果存在，则将数据添加到 children 数组中
              if (existingItem) {
                existingItem.children.push({
                  cnt: item.cnt,
                  percentage: item.percentage,
                  trigger_class: item.trigger_class,
                  trigger_value: item.trigger_value,
                });
              } else {
                // 如果不存在，则创建新的项
                result.push({
                  trigger_class: item.trigger_class,
                  children: [
                    {
                      cnt: item.cnt,
                      percentage: item.percentage,
                      trigger_class: item.trigger_class,
                      trigger_value: item.trigger_value,
                    },
                  ],
                });
              }

              return result;
            }, []);

            return formattedData;
          }
        })
        .catch((res) => {});
    },

    initEchartData() {
      // console.log(this.selectedItems)
      // let proofNum = JSON.parse(sessionStorage.getItem('proof_number'))[0].options[0].proof_num;
      // console.log(proofNum,this.value2);
      let data = {};
      try {
        data = {
          proof_num: this.value1,
          starttime: this.value2[0] ? this.value2[0] / 1000 : 0,
          endtime: this.value2[1] ? this.value2[1] / 1000 : 2000000000,
          trigger_value: this.selectedItems.join(","),
        };
      } catch (error) {
        data = {
          proof_num: this.value1,
          starttime: 0,
          endtime: 2000000000,
          trigger_value: this.selectedItems.join(","),
        };
      }

      getEchartsData(data)
        .then((res) => {
          this.pirData = res.data;
        })
        .catch((err) => {});
    },
    handleEdit(index, row) {
      const proof_num = row.proofNum;
      // const phoneNumber = Number(row.otherPhone);
      let d = row;

      if (row.model == "CallRecords") {
        d.list_offset = 1;
        d.list_limit = 20;
        d.msg_offset = 1;
        d.app_name = d.phone;
        d.account_id = d.ACCOUNT_ID;
        // d.model = d.model,
        d.proof_num = proof_num;
        sessionStorage.setItem("model", "callrecords");
      } else {
        switch (d.model) {
          // case "通讯录":
          //   d.list_offset = 1;
          //   d.list_limit = 20;
          //   d.msg_offset = 1;
          //   d.app_name = d.phone ? d.phone : d.otherPhone;
          //   d.proof_num = proof_num;
          //   break;
          case "sms":
            d.list_offset = 1;
            d.list_limit = 20;
            d.msg_offset = 1;
            d.app_name = d.phone ? d.phone : d.otherPhone;
            d.proof_num = proof_num;
            // row.swarchKey = ;

            break;
          case "wechat":
            d.list_offset = 1;
            d.list_limit = 20;
            d.msg_offset = 1;
            // row.app_name = "好友";
            d.app_name = "好友";
            d.proof_num = proof_num;
            d.account_id = d.ACCOUNT_ID;
            d.username = d.username;
            d.label = d.username;
            d.contact_username = d.CONTACTNAME;
            d.msgtime = d.infoTime;
            d.id = d.maxid;
            break;
          case "qq":
            d.list_offset = 1;
            d.list_limit = 20;
            d.msg_offset = 1;
            // row.app_name = "好友";
            d.app_name = "好友";
            d.proof_num = proof_num;
            d.account_id = d.ACCOUNT_ID;
            d.username = d.USERNAME;
            d.label = d.USERNAME;
            d.contact_username = d.CONTACTNAME;
            d.msgtime = d.infoTime;
            d.id = d.maxid;
            break;
          default:
            break;
        }
        sessionStorage.setItem("model", d.model);
      }
      // 储存类型

      // 储存节点数据
      sessionStorage.setItem("sumData", JSON.stringify(d));
      // 激活跳转组件
      this.$store.commit("SET_ORDERDATA", Date.parse(new Date()));
      sessionStorage.setItem("only", true);
      this.visible = false;
      // this.$router.push({ name: "proofAnalyze"});
      // this.$parent.changeContent();
      this.$emit("changeContent");
    },
    handleDelete(index, row) {
      console.log(index, row);
    },
    focus() {},
    handleChange() {},
    setKeyWord() {
      this.visible = true;
    },
    handleOk() {
      console.log(this.$refs.tagBoxRef.tagList);
    },
  },
};
</script>

<style>
.el-select .el-select-dropdown {
  transform: translateX(-5px);
}
</style>